<template>
  <view class="space-item" @click="handleClick">
    <tm-avatar
      v-if="spaceIcon"
      class="space-item__avatar"
      :size="64"
      :img="spaceIcon"
    />
    <avatar
      v-else
      class="space-item__avatar"
      :userName="spaceName"
      width="64rpx"
      height="64rpx"
      lineHeight="64rpx"
      fontSize="28rpx"
    />
    <text class="space-item__name">{{ spaceName }}</text>
    <tm-icon name="tmicon-angle-right" :font-size="28" color="#97A0B4" />
  </view>
</template>

<script lang="ts" setup>
import { computed, onMounted, onUnmounted, ref } from 'vue'
import orgCtrl from '@/ts/controller'
import avatar from '@/components/avatar/avatar.vue'
import { IBelong } from '@/ts/core'

const emits = defineEmits<{ (e: 'click'): void }>()

const spaceInfo = ref<IBelong>(orgCtrl.home.current)
const subscribeKeys = ref<string[]>([])

const spaceIcon = computed<string>(() => {
  return spaceInfo.value?.share?.avatar?.thumbnail ?? ''
})

const spaceName = computed<string>(() => {
  return spaceInfo.value?.name ?? ''
})

const handleClick = (): void => {
  emits('click')
}

const syncSpaceInfo = (): void => {
  spaceInfo.value = orgCtrl.home.current
}

onMounted(() => {
  const id = orgCtrl.subscribe(() => {
    syncSpaceInfo()
  }, false)
  subscribeKeys.value = [id]
})

onUnmounted(() => {
  if (subscribeKeys.value.length > 0) {
    orgCtrl.unsubscribe(subscribeKeys.value)
  }
})
</script>

<style lang="scss" scoped>
.space-item {
  display: flex;
  align-items: center;
  padding: 16rpx 24rpx;
  border-radius: 16rpx;
  background-color: #fff;
  gap: 24rpx;
}

.space-item__avatar {
  flex-shrink: 0;
}

.space-item__name {
  flex: 1;
  font-size: 28rpx;
  color: #1f2233;
  font-weight: 600;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
</style>
